<template>
    <div class="position-map" :style="{ width: width }">
        <!-- <div class="search-container">
            <input v-model="searchWord" placeholder="请输入关键字进行搜索" style="width: 300px; margin-right: 16px; margin-bottom: 16px" @keyup.enter.native="handleSearch" />
            <button type="primary" size="small" @click="handleSearch">搜索</button>
        </div> -->
        <!--  ak="http://api.map.baidu.com/api?v=2.0&ak=j2sy6K7okugeW8CR00ACyKYXGnRWQGHL&callback=mapInit" -->
        <baidu-map class="map1" :center="center" :zoom="zoom" @ready="handler" :scroll-wheel-zoom="true">
            <!-- 缩放控件 -->
            <bm-navigation v-if="isShowControl" anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
            <!-- 定位控件 -->
            <bm-geolocation v-if="isShowControl" anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation="true" @locationSuccess="locationSuccess"></bm-geolocation>
            <!-- 地区检索 -->
            <bm-local-search :keyword="keyword" :auto-viewport="true" :panel="false" @searchcomplete="handleSearchComplete"></bm-local-search>
            <!-- 地图容器 -->
            <bm-view class="map-container" :style="{ width: '100%', height: height }"></bm-view>
        </baidu-map>
        <!-- <button type="primary" style="margin-top: 16px" @click="confirmPosition">位置选好了，确定标注</button> -->
    </div>
</template>

<script>
import { BaiduMap, BmNavigation, BmView, BmGeolocation, BmLocalSearch } from 'vue-baidu-map'
export default {
    name: 'positionMap',
    components: {
        BaiduMap,
        BmNavigation,
        BmView,
        BmGeolocation,
        BmLocalSearch
    },
    props: {
        width: {
            type: String,
            default: () => '100%'
        },
        initialPosition: {
            type: Object,
            default() {
                return { lng: 114.065953, lat: 22.547656 }
            }
        },
        height: {
            type: String,
            default: '390px'
        },
        isShowControl: {
            type: Boolean,
            default: true
        }
    },
    watch: {
        initialPosition: {
            deep: true,
            immediate: true,
            handler(val) {
                if (val.lng) {
                    this.center = val
                }
            }
        }
    },
    data() {
        return {
            searchWord: '',
            keyword: '',
            center: { lng: 114.065953, lat: 22.547656 },
            zoom: 15,
            locData: {
                longitude: '',
                latitude: ''
            },
            mapInstance: null, // 地图实例
            BMap: null,
        }
    },
    methods: {
        confirmPosition() {
            this.$emit('confirm', this.locData)
        },
        handleSearchComplete(res) {
            if (!res) return
            const info = res.Kr[0]
            const address = info.address
            const { lng, lat } = info.point
            const myPoint = new this.BMap.Point(lng, lat)
            this.showLabelAndMaker(address, lng, lat, myPoint)
        },
        handleSearch() {
            if (!this.searchWord) return
            this.keyword = this.searchWord
        },
        // 地图初始化
        handler({ BMap, map }) {
            this.BMap = BMap
            // const geolocation = new this.BMap.Geolocation()
            // geolocation.getCurrentPosition(
            //     r => {
            //         this.center = { lng: r.longitude, lat: r.latitude } // 设置center属性值
            //     },
            //     { enableHighAccuracy: true }
            // )

            this.mapInstance = map
            this.$emit('complete')
        },
        // 点击地图
        handleClickOld(e) {
            setTimeout(() => {
              const { lng, lat } = e.point
              this.center = { lng, lat }
              const point = new this.BMap.Point(lng, lat)
              const gc = new this.BMap.Geocoder()
              gc.getLocation(point, res => {
                  const address = res.address
                  this.showLabelAndMaker(address, lng, lat, point)
              })
              this.locData.longitude = lng
              this.locData.latitude = lat
            }, 1000);
        },
        handleClick(e) {
            setTimeout(() => {
              const { lng, lat } = e.point
              this.center = { lng, lat }
              const point = new this.BMap.Point(lng, lat)
              this.showMaker(point)
              this.locData.longitude = lng
              this.locData.latitude = lat
            }, 1000);
        },
        showMaker(point) {
            this.mapInstance.clearOverlays()
            // this.mapInstance.clearOverlays()
            const myMarker = new this.BMap.Marker(point)
            this.mapInstance.addOverlay(myMarker)
        },
        // 显示标记点和位置信息标签
        showLabelAndMaker(address, lng, lat, point) {
            this.mapInstance.clearOverlays()
            // const myLabel = new this.BMap.Label(address, { position: point }) // 百度地图文档https://lbsyun.baidu.com/cms/jsapi/reference/jsapi_reference.html#a3b9
            // const content = `
            //         <div style="margin-bottom:16px">坐标: ${lng}, ${lat}</div>
            //         <div>地址: ${address}</div>
            //     `
            // myLabel.setStyle({
            //     fontSize: '14px',
            //     color: 'black',
            //     backgroundColor: '#cccccc',
            //     padding: '8px'
            // })
            // myLabel.setContent(content)
            // this.mapInstance.addOverlay(myLabel)

            const myMarker = new this.BMap.Marker(point)
            this.mapInstance.addOverlay(myMarker)
        },
        // 定位成功回调
        locationSuccess(point) {
            const address = `${point.addressComponent.province}${point.addressComponent.city}`
            const { lng, lat } = point.point
            const myPoint = new this.BMap.Point(lng, lat)
            this.showLabelAndMaker(address, lng, lat, myPoint)
            this.locData.longitude = lng
            this.locData.latitude = lat
        },
        // 检索
        localSearch(keyword) {
            const map = this.mapInstance
            const centerPoint = this.center
            return new Promise((resolve, reject) => {
                const local = new this.BMap.LocalSearch(this.mapInstance,
                {
                    // renderOptions: {map: this.mapInstance, autoViewport: false},
                    onSearchComplete: function(results){
                        console.log('==========')
                        console.log(results)

                        results.as = results.as.map(v => {
                            let dis = map.getDistance(v.point, centerPoint)
                            let strDis = ''
                            if (dis > 1000) {
                                strDis = (dis / 1000).toFixed(1) + 'km'
                            } else {
                                strDis = dis.toFixed(0) + 'm'
                            }

                            return {
                                ...v,
                                dis: strDis,
                                disNum: dis
                            }
                        }).sort((a, b) => a.disNum - b.disNum)

                        // 去重
                        const arr = []
                        const temp = {}
                        results.as.forEach(v => {
                            if (!temp[v.address]) {
                                temp[v.address] = 1
                                arr.push(v)
                            }
                        })
                        results.as = arr

			            resolve(results)
		            }
                });

                const {lng, lat} = this.center
                const myPoint = new this.BMap.Point(lng, lat)
                local.searchNearby(keyword, myPoint, 3000);
            })
        },
        // 计算方位
        getDirDescription(pt1, pt2){
            var h = pt1.lng - pt2.lng;
            var v = pt1.lat - pt2.lat;
            if (Math.abs(h) > Math.abs(v)){
                return h < 0 ? "西" : "东";
            }
            else {
                return v < 0 ? "南" : "北";
            }
        }
    }
}
</script>
<style lang="less" scoped>
.position-map {
    text-align: center;
}
.search-container {
    text-align: left;
}
</style>
